<?php
namespace app\common\model\order;

use app\common\model\BaseModel;
use app\common\model\car\Car;

/**
 * 分配车辆
 */
class CarOrderPlan extends BaseModel
{
    protected $pk = 'id';
    protected $name = 'car_order_plan';

    public function plan($id,$car)
    {
        //检查车辆是否已分配

        $data = array();
        $arr = [];
        foreach($car as $k=>$v){
            $arr[] = $v['car_id'];
            $car_model = new Car();

            $driver = $car_model->alias('c')
            ->field('m.realname,u.mobile')
                ->join('jjjshop_user u','c.user_id=u.user_id','left')
                ->join('jjjshop_my_driver m','c.driver_id=m.id','left')
                ->where(array('c.car_id'=>$v['car_id']))
                ->find();

            $data[$k]['driver_name'] = $driver['realname'];
            $data[$k]['driver_phone'] = $driver['mobile'];
            $data[$k]['order_id'] = $id;
            $data[$k]['car_id'] = $v['car_id'];
            $data[$k]['create_time'] = time();
        }
        $t = time();
        $w[] = ['cp.car_id','in',$arr];
        //$w[] = ['status','=',1];
        $w[] = ['co.star_time','<',$t];
        $w[] = ['co.end_time','>',$t];
        $res = $this->alias('cp')
            ->join("jjjshop_car_order co",'cp.order_id=co.id','left')
            ->where($w)->find();

        if($res){
            $this->error = '所选车辆有在使用中';
            return false;
        }
        //dump($data);die;
        $res = $this->insertAll($data);
        if($res){
            return true;
        }
        $this->error = '分配车辆失败';
        return false;
    }
}